import dbx;
import webx;
import stdx;
import json;
import pdfkit;

def main(app):
	res = {'code': stdx.XG_FAIL};

	title = '';
	content = app.getParameter('content');
	if len(content) > 0:
		title = webx.GetSequence();
		path = 'dat/pub/' + title + '.htm';
		with open(webx.GetPath() + path, "w+") as file:
			file.write(content);
		url = '%s/singlepage?path=/%s&background=none' % (app.getVariable('WEBSITE'), path);
	else:
		url = app.getParameter('id');
		dbid = app.getParameter('dbid');
		user = app.getSessionList(('USER'));
		if isinstance(user, int): res['code'] = user;
		elif len(user[0]) <= 0: res['code'] = stdx.XG_TIMEOUT;
		else:
			data = None;
			if url:
				with app.dbconnect(dbid) as db: data = db.queryArray('SELECT USER,LEVEL,TITLE FROM T_XG_NOTE WHERE ID=%s' % url);
				url = '%s/sharenote?sid=%s&dbid=%s&id=%s&background=none' % (app.getVariable('WEBSITE'), app.getSessionId(), dbid, url);
			else:
				res['code'] = stdx.XG_PARAMERR;
			if data and len(data) > 0:
				data = data[0];
				if data['user'] == user[0] or int(data['level']) > 2:
					title = data['title'];
				else: res['code'] = stdx.XG_AUTHFAIL;

	if len(title) > 0:
		path = 'dat/pub/' + webx.GetSequence() + '.pdf';
		res['code'] = stdx.XG_OK;
		res['link'] = '/' + path;
		res['name'] = title + '.pdf';
		try:
			pdfkit.from_url(url, webx.GetPath() + path);
			app.trace('INF', 'save pdf[%s] from url[%s] success' % (path, url));
		except BaseException as e:
			app.trace('ERR', 'save pdf from url[%s] failed[%s]' % (url, str(e)));

	return stdx.json(res);